package com.wxw.BaseLibrary.http;

import android.app.Activity;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.SyncHttpClient;
import com.wxw.BaseLibrary.element.JsonObject;
import com.wxw.BaseLibrary.element.JsonProperty;
import com.wxw.BaseLibrary.element.JsonPropertyType;
import com.wxw.BaseLibrary.tool.FileUtil;
import com.wxw.BaseLibrary.tool.PHONE_STATE;
import com.wxw.BaseLibrary.tool.PhoneState;
import lombok.Getter;
import lombok.Setter;
import org.apache.http.Header;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class LogUploadProcessor extends DefaultHttpRequestProcessor {
    private Activity parentActivity;
    private String logType;
    private String filePath;
    private boolean running;
    private boolean uploading;
    private RequestParams params;
    private List<File> uploadedList = new ArrayList<>();
    private SyncHttpClient client = new SyncHttpClient();
    private JsonProperty returnMsg = new JsonProperty();
    private String url;
    @Setter
    @Getter
    private boolean deleteFile;
    @Getter
    @Setter
    private JsonObject uploadParam;

    public LogUploadProcessor(Activity activity, String url, String logType, String path) {
        this.parentActivity = activity;
        this.url = url;
        this.logType = logType;
        this.filePath = FileUtil.joinPath(path, logType);
    }

    public LogUploadProcessor(Activity activity, String url, String logType) {
        this(activity, url, logType, "error");
    }

    public LogUploadProcessor(Activity activity, String url) {
        this(activity, url, "error");
    }

    public LogUploadProcessor(Activity activity) {
        this(activity, "error");
    }

    @Override
    public void start() {
        if (sendThread != null) {
            sendThread.start();
        }
    }

    @Override
    public void stop() {
        running = false;
        uploading = false;
    }

    private Thread sendThread = new Thread(new Runnable() {
        @Override
        public void run() {
            running = true;
            try {
                if (uploadParam == null) {
                    uploadParam = new JsonObject();
                }
                uploadParam.setProperty("Phone", new JsonProperty("'" + PhoneState.getPhoneState(PHONE_STATE.DeviceId, parentActivity).toString() + "'"));
                uploadParam.setProperty("logType", new JsonProperty(logType));
                try {
                    File file = new File(filePath);
                    if (file.isDirectory() && file.listFiles().length > 0) {
                        for (File f : file.listFiles()) {
                            if (f.isFile() && f.exists()) {
                                params = new RequestParams();
                                uploadParam.setProperty("fname", new JsonProperty(f.getName()));
                                params.put("info", uploadParam.toString());
                                params.put("file", f);
                                doUpload();
                                uploadedList.add(f);
                            }
                            while (uploading) {
                                Thread.sleep(1000);
                            }
                            if (!running) {
                                client.cancelAllRequests(true);
                                break;
                            }
                        }
                        if (deleteFile && uploadedList.size() > 0) {
                            for (File f : uploadedList) {
                                f.delete();
                            }
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                if (returnMsg.getType() == JsonPropertyType.Array && returnMsg.getItems().size() > 0) {
                    triggerEvent(null, returnMsg.toString());
                }
            } catch (Exception e) {
                triggerEvent(null, "上传错误日志异常:" + e.getMessage());
            }
        }
    });

    private void doUpload() {
        uploading = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                client.post(url, params, new AsyncHttpResponseHandler() {
                    @Override
                    public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                        String s = "";
                        if (bytes != null && bytes.length > 0) {
                            s = new String(bytes);
                            s = RequestMessage.getHttpResponseContent(s);
                        } else {
                            s = "连接服务器超时，服务器当前无法连接！";
                        }
                        JsonObject j = new JsonObject();
                        j.setProperty("upload_error", new JsonProperty(s));
                        returnMsg.add(j);
                        uploading = false;
                    }

                    @Override
                    public void onSuccess(int i, Header[] headers, byte[] bytes) {
                        String s = new String(bytes);
                        s = RequestMessage.getHttpResponseContent(s);
                        try {
                            returnMsg.add(new JsonObject(s));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        uploading = false;
                    }

                    @Override
                    public void onProgress(long bytesWritten, long totalSize) {
                        super.onProgress(bytesWritten, totalSize);
                    }
                });
            }
        }).start();
    }
}